package com.zxx.casserver.modules.permission.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Joiner;
import com.zxx.cascommon.base.exception.DataNoChangeException;
import com.zxx.cascommon.base.exception.DataNotExistException;
import com.zxx.casserver.base.common.UserConstants;
import com.zxx.casserver.modules.permission.entity.PermissionDO;
import com.zxx.casserver.modules.permission.entity.PermissionVO;
import com.zxx.casserver.modules.permission.mapper.PermissionMapper;
import com.zxx.casserver.modules.permission.service.IPermissionService;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zhoukai
 * @since 2020-08-03
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, PermissionDO> implements IPermissionService {

    @Override
    public IPage<PermissionDO> listPermission(PermissionVO permissionVO) {
        Page<PermissionDO> page = new Page<>(permissionVO.getCurPage(), permissionVO.getPageSize());
        QueryWrapper<PermissionDO> queryWrapper = new QueryWrapper<>();
        if (!ObjectUtils.isEmpty(permissionVO.getIds())) {
            queryWrapper.in("permission_id", permissionVO.getIds());
        }
        if (!ObjectUtils.isEmpty(permissionVO.getPermissionId())) {
            queryWrapper.eq("permission_id", permissionVO.getPermissionId());
        }
        if (!ObjectUtils.isEmpty(permissionVO.getAppId())) {
            queryWrapper.eq("app_id", permissionVO.getAppId());
        }
        if (!ObjectUtils.isEmpty(permissionVO.getPcode())) {
            queryWrapper.eq("pcode", permissionVO.getPcode());
        }
        if (!ObjectUtils.isEmpty(permissionVO.getLevel())) {
            queryWrapper.eq("level", permissionVO.getLevel());
        }
        if (!ObjectUtils.isEmpty(permissionVO.getType())) {
            queryWrapper.le("type", permissionVO.getType());
        }
        if (!ObjectUtils.isEmpty(permissionVO.getStatus())) {
            queryWrapper.le("status", permissionVO.getStatus());
        }
        if (!ObjectUtils.isEmpty(permissionVO.getUrl())) {
            queryWrapper.le("url", permissionVO.getUrl());
        }
        if (!ObjectUtils.isEmpty(permissionVO.getColumns()) && !ObjectUtils.isEmpty(permissionVO.getAsc())) {
            String columnNames = Joiner.on(",").join(permissionVO.getColumns());
            if (permissionVO.getAsc()) {
                queryWrapper.orderByAsc(columnNames);
            } else {
                queryWrapper.orderByDesc(columnNames);
            }
        } else {
            queryWrapper.orderByAsc("sort");
        }
        return page(page, queryWrapper);
    }

    @Override
    public PermissionDO savePermission(PermissionVO permissionVO) {
        PermissionDO permissionDO = JSON.parseObject(JSON.toJSONString(permissionVO), PermissionDO.class);
        permissionDO.setCreateTime(System.currentTimeMillis());
        permissionDO.setUpdateTime(System.currentTimeMillis());
        if (ObjectUtils.isEmpty(permissionDO.getPcode())
                || UserConstants.PERMISSION_ROOT.equals(permissionDO.getPcode())) {
            permissionDO.setPcode(UserConstants.PERMISSION_ROOT);
            permissionDO.setPcodes("[" + permissionDO.getPcode() + "]");
        } else {
            //查询上级节点
            PermissionDO parentPermission = getById(permissionDO.getPcode());
            if (ObjectUtils.isEmpty(parentPermission)) {
                return null;
            }
            permissionDO.setPcodes(parentPermission.getPcodes() + ",[" + permissionDO.getPcode() + "]");
            permissionDO.setLevel(parentPermission.getLevel() + 1);
        }
        boolean isSave = save(permissionDO);
        if (isSave) {
            return permissionDO;
        }
        return null;
    }

    @Override
    public PermissionDO updatePermission(PermissionVO permissionVO) {
        PermissionDO oldPermission = getById(permissionVO.getPermissionId());
        if (ObjectUtils.isEmpty(oldPermission)) {
            throw new DataNotExistException();
        }
        PermissionDO permissionDO = checkChange(permissionVO, oldPermission);
        if (ObjectUtils.isEmpty(permissionDO)) {
            throw new DataNoChangeException();
        }
        boolean isUpdate = updateById(permissionDO);
        if (isUpdate) {
            return permissionDO;
        }
        return null;
    }

    @Override
    public PermissionDO removePermission(PermissionVO permissionVO) {
        PermissionDO oldPermission = getById(permissionVO.getPermissionId());
        if (ObjectUtils.isEmpty(oldPermission)) {
            throw new DataNotExistException();
        }
        boolean isDelete = removeById(permissionVO.getPermissionId());
        if (isDelete) {
            return oldPermission;
        }
        return null;
    }

    /**
     * 比较传入的参数是否有值修改
     *
     * @param permissionVO
     * @param oldPermission
     * @return
     */
    private PermissionDO checkChange(PermissionVO permissionVO, PermissionDO oldPermission) {
        PermissionDO permissionDO = new PermissionDO();
        permissionDO.setPermissionId(permissionVO.getPermissionId());
        permissionDO.setUpdateTime(System.currentTimeMillis());

        boolean isChange = false;

        //判断是否变更上级节点，如果上级节点变更，则需要重新变更
        if (!ObjectUtils.isEmpty(permissionVO.getPcode()) &&
                !permissionVO.getPcode().equals(oldPermission.getPcode())) {
            //查询上级节点
            PermissionDO permission = getById(oldPermission.getPcode());
            if (ObjectUtils.isEmpty(permission)) {
                throw new DataNotExistException();
            }
            permissionDO.setPcodes(permission.getPcodes() + ",[" + permissionVO.getPcode() + "]");
            permissionDO.setLevel(permission.getLevel() + 1);
            isChange = true;
        }

        if (!ObjectUtils.isEmpty(permissionVO.getName()) && !permissionVO.getName().equals(oldPermission.getName())) {
            permissionDO.setName(permissionVO.getName());
            isChange = true;
        }
        if (!ObjectUtils.isEmpty(permissionVO.getUrl()) && !permissionVO.getUrl().equals(oldPermission.getUrl())) {
            permissionDO.setUrl(permissionVO.getUrl());
            isChange = true;
        }
        if (!ObjectUtils.isEmpty(permissionVO.getType()) && !permissionVO.getType().equals(oldPermission.getType())) {
            permissionDO.setType(permissionVO.getType());
            isChange = true;
        }
        if (!ObjectUtils.isEmpty(permissionVO.getStatus()) && !permissionVO.getStatus().equals(oldPermission.getStatus())) {
            permissionDO.setType(permissionVO.getStatus());
            isChange = true;
        }
        if (!ObjectUtils.isEmpty(permissionVO.getPcode()) && !permissionVO.getPcode().equals(oldPermission.getPcode())) {
            permissionDO.setPcode(permissionVO.getPcode());
            isChange = true;
        }
        if (!ObjectUtils.isEmpty(permissionVO.getShowStatus()) && !permissionVO.getShowStatus().equals(oldPermission.getShowStatus())) {
            permissionDO.setShowStatus(permissionVO.getShowStatus());
            isChange = true;
        }
        if (!ObjectUtils.isEmpty(permissionVO.getSort()) && !permissionVO.getSort().equals(oldPermission.getSort())) {
            permissionDO.setSort(permissionVO.getSort());
            isChange = true;
        }
        return isChange ? permissionDO : null;
    }
}
